package com.example.config;

import com.example.common.BaseProperties;
import com.example.pojo.SessionMessage;
import com.example.service.SessionMessageService;
import com.example.service.SessionService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 管理会话的历史记录
 */
@Component
@AllArgsConstructor
public class GlobalChatMemoryRepository implements ChatMemoryRepository {
    private final SessionService sessionService;
    private final SessionMessageService sessionMessageService;
    private final GlobalMemory globalMemory;
    @Override
    public List<String> findConversationIds() {
        return sessionService.list().stream().map(message -> message.getSessionId()).toList();
    }

    @Override
    public List<Message> findByConversationId(String conversationId) {
        List<SessionMessage> list = sessionMessageService.getSessionMessageList(conversationId);
        if (ObjectUtils.isEmpty(list)){
            return List.of();
        }
        return list.stream().map(BaseProperties::convertToMessage).flatMap(List::stream).toList();
    }



    @Override
    public void saveAll(String conversationId, List<Message> messages) {
        globalMemory.add(conversationId, messages);
    }

    @Override
    public void deleteByConversationId(String conversationId) {
        sessionMessageService.deleteSessionMessage(conversationId);
    }
}
